package org.rsbot.script.randoms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.rsbot.bot.Bot;
import org.rsbot.gui.AccountManager;
import org.rsbot.script.Random;
import org.rsbot.script.ScriptManifest;
import org.rsbot.script.wrappers.RSInterface;
import org.rsbot.util.GlobalConfiguration;

/**
 * Simple login bot made by Gnarly for RSBot
 * 
 * (c)2010 Gnarly
 * Nobody except Gnarly has permission to edit this script!
 * 
 * @author Gnarly
 */
@ScriptManifest(authors = { "Gnarly" }, name = "LoginBot", version = 3.3)
public class LoginBot extends Random {

	private static final int LOGIN_SCREEN = 744;
	private static final int LOGIN_SCREEN_USERNAME_INTERFACE = 452;
	private static final int LOGIN_SCREEN_PASSWORD_INTERFACE = 458;
	private static final int LOGIN_SCREEN_BUTTON_LOGIN = 467;
	private static final int LOGIN_SCREEN_RETURN_TEXT = 446;

	private String accountUsername;
	private String usernameTried;

	private int failSafeCount;

	@Override
	public boolean activateCondition() {
		accountUsername = Bot.getAccountName().replaceAll("_", " ").toLowerCase().trim();
		usernameTried = "";
		failSafeCount = 0;
		return !isLoggedIn();
	}

	@Override
	public int loop() {
		if (isLoggedIn()) {
			log("Waiting to be fully logged in.");
			if (random(0, 1) == 0) {
				randomMove();
			}
			while (!isWelcomeScreen()) {
				wait(500);
			}
			return -1;
		}
		if (failSafeCount > 19) {
			log("Stopping all scripts. Exceeded amount of login attempts.");
			stopScript();
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("update")) {
			log("There was a update. Stopping all scripts!");
			randomMove();
			stopScript();
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("disable")) {
			log("Sorry buddy. Your account is banned.");
			randomMove();
			stopScript();
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("members")) {
			log("Please login to a free world or use a members account.");
			stopScript();
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("incorrect")) {
			log("Failed to login five times in a row. Stopping all scripts.");
			stopScript();
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("invalid")) {
			failSafeCount++;
			randomMove();
			wait(random(500, 2000));
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("full")) {
			if (failSafeCount > 5) {
				failSafeCount -= 5;
			}
			wait(randomWait());
		}
		if (RSInterface.getInterface(744).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("error connecting")) {
			boolean connected = false;
			log("Internet connection lost, waiting for connection.");
			while (!connected) {
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(GlobalConfiguration.getURLConnection(new URL("http://www.runescape.com"), null).getInputStream()));
					String contents = "";
					String s = "";
					while ((s = reader.readLine()) != null) {
						contents = contents.concat(s);
					}
					if (contents != null) {
						log("Connection restored!");
						connected = true;
					}
				} catch (final Exception e) {
					log("Unable to connect, retrying connection");
					wait(random(5000, 10000));
				}
			}
		}
		if (RSInterface.getInterface(LOGIN_SCREEN).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("world"))
			return randomWait();
		if (RSInterface.getInterface(LOGIN_SCREEN).getChild(LOGIN_SCREEN_RETURN_TEXT).getText().toLowerCase().contains("performing login"))
			return randomWait();
		int propertyType = 0;
		if (isLoginScreen()) {
			int tries = 0;
			while (true) {
				tries++;
				if (RSInterface.getInterface(LOGIN_SCREEN).getChild(LOGIN_SCREEN_USERNAME_INTERFACE).getText().endsWith("|")) {
					propertyType = 1;
					break;
				}
				if (RSInterface.getInterface(LOGIN_SCREEN).getChild(LOGIN_SCREEN_PASSWORD_INTERFACE).getText().endsWith("|")) {
					propertyType = 2;
					break;
				}
				if (tries == 50) {
					break;
				}
				wait(random(10, 20));
			}
			if (propertyType == 0) {
				atInterface(LOGIN_SCREEN, LOGIN_SCREEN_BUTTON_LOGIN);
			}
			if (propertyType == 1) {
				sendAccountProperty(accountUsername, LOGIN_SCREEN_USERNAME_INTERFACE);
			}
			if (propertyType == 2) {
				sendAccountProperty(AccountManager.getPassword(Bot.getAccountName()), LOGIN_SCREEN_PASSWORD_INTERFACE);
			}
		}
		return random(250, 500);
	}

	private void sendAccountProperty(String data, int type) {
		if (type == LOGIN_SCREEN_PASSWORD_INTERFACE) {
			if (!usernameTried.equals(accountUsername)) {
				atInterface(LOGIN_SCREEN, LOGIN_SCREEN_USERNAME_INTERFACE);
				return;
			}
		}
		String boxText = RSInterface.getInterface(LOGIN_SCREEN).getChild(type).getText().trim();
		if (boxText.endsWith("|")) {
			boxText = boxText.substring(0, boxText.length() - 1);
		}
		if (type == LOGIN_SCREEN_USERNAME_INTERFACE) {
			if (boxText.equalsIgnoreCase(data)) {
				sendText("", true);
				return;
			}
		} else {
			if (boxText.length() == data.length()) {
				sendText("", true);
				return;
			}
		}
		if ((boxText.length() > 0) && (boxText.length() != data.length())) {
			for (int i = 0; i <= boxText.length() + random(0, 3); i++) {
				sendText("\b", false);
				if (random(0, 2) == 0) {
					wait(random(1, 2));
				}
			}
		}
		if (type == LOGIN_SCREEN_USERNAME_INTERFACE) {
			usernameTried = data;
		}
		sendText(data, false);
		sendAccountProperty(data, type);
	}

	private int randomWait() {
		return random(50, 100);
	}

	private void randomMove() {
		if (random(0, 1) == 0) {
			moveMouseSlightly();
		}
	}

}